#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int decode(Scalar color) {
    const Scalar colors[] = {
        Scalar(0, 0, 0),      // 0
        Scalar(255, 255, 255),// 1
        Scalar(0, 0, 255),   // 2
        Scalar(255, 0, 0),   // 3
        Scalar(0, 255, 0),   // 4
        Scalar(255, 0, 255), // 5
        Scalar(0, 255, 255), // 6
        Scalar(255, 255, 0)  // 7
    };

    int min_idx = 0;
    double min_dist = norm(color - colors[0]);
    for (int i = 1; i < 8; ++i) {
        double dist = norm(color - colors[i]);
        if (dist < min_dist) {
            min_dist = dist;
            min_idx = i;
        }
    }
    return min_idx;
}

int receive() {
    VideoCapture cap(0);
    if (!cap.isOpened()) return -1;

    Mat frame;
    cap >> frame;
    if (frame.empty()) return -1;

    Rect roi(frame.cols / 2 - 50, frame.rows / 2 - 50, 100, 100);
    Mat center = frame(roi);
    Scalar avg_color = mean(center);

    return decode(avg_color);
}

int main() {
    while (true) {
        int value = receive();
        cout << "Received value: " << value << endl;
        if (waitKey(1000) == 27) break;
    }
    return 0;
}